package servlet;

import anno.Autowired;
import anno.RequestBody;
import anno.ResponseBody;
import dao.OrderDAO;
import pojo.Order;
import utils.ApiResult;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.sql.SQLException;
import java.util.Map;

@WebServlet("/order")
public class OrderServlet extends BaseServlet {

    @Autowired
    private OrderDAO orderDAO;

    /**
     * 添加订单
     *
     * @param req   请求对象
     * @param resp  响应对象
     * @param order 订单对象
     * @return ApiResult 响应结果
     * @throws SQLException SQL异常
     */
    @ResponseBody
    public ApiResult addOrder(HttpServletRequest req, HttpServletResponse resp, @RequestBody Order order) throws SQLException {
        orderDAO.insert(order);
        return new ApiResult(200, "订单添加成功", null);
    }

    /**
     * 更新订单
     *
     * @param req   请求对象
     * @param resp  响应对象
     * @param order 订单对象
     * @return ApiResult 响应结果
     * @throws SQLException SQL异常
     */
    @ResponseBody
    public ApiResult updateOrder(HttpServletRequest req, HttpServletResponse resp, @RequestBody Order order) throws SQLException {
        orderDAO.update(order);
        return new ApiResult(200, "订单更新成功", null);
    }

    /**
     * 删除订单
     *
     * @param req  请求对象
     * @param resp 响应对象
     * @param id   订单ID
     * @return ApiResult 响应结果
     * @throws SQLException SQL异常
     */
    @ResponseBody
    public ApiResult deleteOrder(HttpServletRequest req, HttpServletResponse resp, String id) throws SQLException {
        orderDAO.deleteById(Integer.parseInt(id));
        return new ApiResult(200, "订单删除成功", null);
    }

    /**
     * 根据ID查询订单
     *
     * @param req  请求对象
     * @param resp 响应对象
     * @param id   订单ID
     * @return ApiResult 响应结果
     * @throws SQLException SQL异常
     */
    @ResponseBody
    public ApiResult getOrderById(HttpServletRequest req, HttpServletResponse resp, String id) throws SQLException {
        Order order = orderDAO.findById(Integer.parseInt(id));
        return new ApiResult(200, "订单查询成功", order);
    }

    /**
     * 分页模糊查询订单
     *
     * @param req      请求对象
     * @param resp     响应对象
     * @param keyword  模糊查询关键字
     * @param pageNum  当前页码
     * @param pageSize 每页记录数
     * @param userId   用户ID，如果为null则代表管理员查询所有订单
     * @return ApiResult 响应结果
     * @throws SQLException SQL异常
     */
    @ResponseBody
    public ApiResult findOrdersByPageAndUserId(HttpServletRequest req, HttpServletResponse resp, String keyword, String pageNum, String pageSize, String userId) throws SQLException {
        int page = Integer.parseInt(pageNum);
        int size = Integer.parseInt(pageSize);
        Integer userIdInt = userId != null && !userId.isEmpty() ? Integer.parseInt(userId) : null;
        Map<String, Object> result = orderDAO.findOrdersByPageAndUserId(keyword, page, size, userIdInt);
        return new ApiResult(200, "分页模糊查询订单成功", result);
    }
}